//
//  WeekdayView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/29.
//



import SwiftUI

struct WeekdayPicker: View {
    var backGroundColor:Color
    @State private var selectedWeekday: Int = Calendar.current.component(.weekday, from: Date()) - 1
    @State private var selectedDate: Date = Date()
    var onDateSelected: (Date) -> Void
    let weekdays = ["日", "一", "二", "三", "四", "五", "六"]
    var body: some View {
        VStack {
            // 显示选中的年月日
//            Text(dateFormatter.string(from: selectedDate))
//                .font(.headline)
//                .padding(.bottom, 10)
            // 星期选择器
            HStack(spacing: 0) {
                ForEach(0..<7) { index in
                    Button(action: {
                        selectedWeekday = index
                        updateSelectedDate()
                        onDateSelected(selectedDate)
                    }) {
                        if selectedWeekday == index {
                            Text(weekdays[index])
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 12)
                                .background(Circle()
                                    .fill(backGroundColor)
                                    .frame(width: 32, height: 32))
                                .foregroundColor(.white)
                        }else {
                            Text(weekdays[index])
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 12)
                                .background(.clear)
                                .foregroundColor(.white)
                        }
                    }
                }
            }
        }
    }
    
    private func updateSelectedDate() {
        let calendar = Calendar.current
        let today = Date()
        let currentWeekday = calendar.component(.weekday, from: today) - 1
        let daysToAdd = selectedWeekday - currentWeekday
        selectedDate = calendar.date(byAdding: .day, value: daysToAdd, to: today) ?? today
    }
    
    private var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日"
        formatter.locale = Locale(identifier: "zh_CN")
        formatter.timeZone = TimeZone.current
        return formatter
    }
}

